package com.erp.app.report.genericInquiry;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionServlet;

import com.erp.app.common.ProjectConstants;
import com.erp.app.report.genericInquiry.inquiryCriteria.beans.vo.InquiryCriteriaVO;
import com.erp.app.report.genericInquiry.inquiryDisplay.beans.vo.InquiryDisplayVO;
import com.erp.app.report.genericInquiry.inquiryMaster.beans.GenericInquiryMasterVO;
import com.erp.app.report.genericInquiry.inquiryOutput.beans.vo.InquiryOutputVO;
import com.erp.app.report.genericInquiry.inquirySp.beans.vo.InquirySpVO;
import com.erp.app.util.web.WebUtil;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;

public class GenericInquiryCSVGenerator extends GenericFileGenerator {
    public GenericInquiryCSVGenerator(GenericInquirySearchForm form) {
		super(form);
	}

	protected void preprocess(
			HttpServletRequest request, 
			HttpServletResponse response,
            ActionServlet servlet, 
            ActionErrors errors) {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=\"" 
                + CommonUtil.toValidFileName(form.getFilename())
                + ProjectConstants.FILE_TYPE_CSV_EXTENSION + "\"");
    }
	
	public void generate(
			ActionMapping mapping, 
			HttpServletRequest request, 
			HttpServletResponse response, 
			ActionServlet servlet, 
			ActionErrors errors) {
    	OutputStream dest = null;
        
        try {
            dest = response.getOutputStream();
            preprocess(request, response, servlet, errors);
            response.setStatus(HttpServletResponse.SC_OK);
            
            ByteArrayOutputStream baos = createReportByteArray(GenericInquiryConstants.JAVA_TYPE_CSV, false, mapping, request, response, servlet, errors);
            
            if (baos == null)
            	getDefaultImpl(dest, request);
            else
            	dump(dest, baos);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
            Logger.logExceptions(e);
        } finally {
            if(form.getReportResultList() != null) {
                form.getReportResultList().clear();
                form.setReportResultList(null);
            }
        }
	}

    private void getDefaultImpl(
    		OutputStream dest,
    		HttpServletRequest request) throws IOException {
    	
    	BufferedOutputStream bos = new BufferedOutputStream(dest);
    	OutputStreamWriter osw = new OutputStreamWriter(bos);
    	
    	HttpSession session = request.getSession(false);
        
    	//StringBuffer rslt = new StringBuffer();
        //StringBuffer critSB = new StringBuffer();
        //StringBuffer headerSB = new StringBuffer();
        //StringBuffer contentSB = new StringBuffer();
        
        GenericInquiryMasterVO vo = form.getGenericInquiryMasterVO();
        Collection spList = vo.getLocalChilds(InquirySpVO.class);
        Collection displayList = vo.getLocalChilds(InquiryDisplayVO.class);
        Collection critList = vo.getLocalChilds(InquiryCriteriaVO.class);
        Collection rsltList = form.getReportResultList();
        InquiryDisplayVO displayVO = null;
        InquiryOutputVO rsltVO = null;
        InquirySpVO spVO = (InquirySpVO)spList.iterator().next();
        InquiryCriteriaVO critVO = null;

        boolean headerGenerated = false;
        boolean firstColumn = true;
        
        // Title
        
        try {
	        osw.write(CommonUtil.toCSVToken(spVO.getInquiryName()) + "\r\n\r\n");
	        
	        Date now = new Date();
	        Format formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss ");
	        Format fDateFormatter = new SimpleDateFormat("ddMMyyyyHHmmss");
	        String today = formatter.format(now);   
	        
	        // Date
	        osw.write("Date:," + CommonUtil.toCSVToken(today) + "\r\n");
	        osw.write("Company:," + CommonUtil.toCSVToken(WebUtil.getAppropriateCompanyCode(session, null)) + "\r\n\r\n");
	        
	        // Search Criteria
	        int counter = 0;
	        for (Iterator critIt = critList.iterator(); critIt.hasNext();) {
	            critVO = (InquiryCriteriaVO)critIt.next();
	            
	            if (critVO.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_TEXT_FM_TO)
	            		|| GenericInquiryConstants.FIELD_TYPE_TEXT_FM_TO_OC.equals(critVO.getFieldType())) {
	                osw.write("From " + CommonUtil.toCSVToken(critVO.getFieldName() + ":"));
	                osw.write("," + CommonUtil.toCSVToken(form.getSrchFrom()[counter]));
	                osw.write(", To " + CommonUtil.toCSVToken(critVO.getFieldName() + ":"));
	                osw.write("," + CommonUtil.toCSVToken(form.getSrchTo()[counter]) + "\r\n");
	            } else if (critVO.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_DROP_DOWN) ||
	                        critVO.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_DROP_DOWN_OC) ||
	                        critVO.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_MULTIPLE_DROP_DOWN) ||
	                        critVO.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_MULTIBOX) ||
	                        critVO.getFieldType().equals(GenericInquiryConstants.FIELD_TYPE_MULTIBOX_HORIZONTAL)) {
	                osw.write(CommonUtil.toCSVToken(critVO.getFieldName() + ":"));
	                osw.write("," + CommonUtil.toCSVToken(form.getSrchFromLabel()[counter]) + "\r\n");
	            } else {
	                osw.write(CommonUtil.toCSVToken(critVO.getFieldName() + ":"));
	                osw.write("," + CommonUtil.toCSVToken(form.getSrchFrom()[counter]) + "\r\n");
	            }
	            counter++;
	        }
	        
	        osw.write("\r\n\r\n");
	        
	        counter = 0;
	        for (Iterator displayIt = displayList.iterator(); displayIt.hasNext();) {
	            displayVO = (InquiryDisplayVO)displayIt.next();
	            
	            if (counter > 0)
	            	osw.write(",");
	            
	            osw.write(CommonUtil.toCSVToken(displayVO.getDispName()));
	            counter++;
	        }
	        osw.write("\r\n");
	            
			for (Iterator rsltIt = rsltList.iterator(); rsltIt.hasNext();) {
			    rsltVO = (InquiryOutputVO)rsltIt.next();
			    firstColumn = true;
			    counter = 0;
			    for (Iterator displayIt = displayList.iterator(); displayIt.hasNext();) {
			        displayVO = (InquiryDisplayVO)displayIt.next();
			
			        String dispCode = displayVO.getDispCode(); 
			        osw.write(firstColumn ? "" : ",");
			        osw.write(CommonUtil.toCSVToken(rsltVO.getField(counter)));
			        firstColumn = false;
			        counter++;
			    }
			    osw.write("\r\n");
			}
        } catch (IOException e) {
        	throw e;
        } finally {
        	if (osw != null) {
        		osw.flush();
        		osw.close();
        	}
        }
    }

	protected ByteArrayOutputStream genContent(ActionMapping mapping, HttpServletRequest request, HttpServletResponse response, ActionServlet servlet, ActionErrors errors) throws Exception {
		return null;
	}
}
